<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    destroyOnClose
    title="选择责任主管"
    :width="500"
    @ok="handleSubmit"
  >
    <BasicForm
      @register="registerForm"
      name="PeiheZhuguanForm"
      :schemas="formSchema"
    />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import type { FormSchema } from '/@/components/Form/src/types/form';
import { useMessage } from '/@/hooks/web/useMessage';
import{ peihezhuguanList, choosePeihezhuguan } from '../Yuedupeihebumenbiao.api';

//  定义类型
interface ZhuGuanUser {
  id: string;
  realname: string;
}

const { createMessage } = useMessage();
const emit = defineEmits(['success']);

//  数据定义
const zhuGuanList = ref<ZhuGuanUser[]>([]);
const taskId = ref<string>('');

//  表单
const [registerForm, { resetFields, validate }] = useForm({
  labelWidth: 120,
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
});

// 弹窗
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data: { id?: string } = {}) => {
  resetFields();
  taskId.value = data.id || '';
  await fetchZhuGuanList(); // 加载主管列表
});

// 获取责任主管列表
const fetchZhuGuanList = async () => {
  try {
    const response = await peihezhuguanList();
    //
    zhuGuanList.value = response || [];
  } catch (error) {
    createMessage.error('获取责任主管列表失败');
  }
};

// 下拉选项动态计算
const options = computed(() =>
  zhuGuanList.value.map((user) => ({
    label: user.realname,
    value: user.id,
  })),
);

//表单 schema（动态绑定 options）
const formSchema = computed<FormSchema[]>(() => [
  {
    field: 'peihezhuguan',
    label: '责任主管',
    component: 'Select',
    required: true,
    componentProps: {
      options: options.value,
      placeholder: '请选择责任主管',
    },
  },
]);

// 提交
const handleSubmit = async () => {
  if (!taskId.value) {
    createMessage.error('任务ID不存在');
    return;
  }

  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });

    await choosePeihezhuguan({
      id: taskId.value,
      peihezhuguan: values.peihezhuguan,
    });

    createMessage.success('选择责任主管成功');
    closeModal();
    // 传递选择的主管ID给父组件
    emit('success', {
      success: true,
      peihezhuguan: values.peihezhuguan
    });
  } catch (error: any) {
    createMessage.error(error?.message || '操作失败');
  } finally {
    setModalProps({ confirmLoading: false });
  }
};
</script>
